package com.yamin.picToCharPaint.utils.image.impl;

import com.yamin.picToCharPaint.utils.image.AbstractImage;
import com.yamin.picToCharPaint.utils.image.IPicToStrPic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @description:
 * @author：yamin
 * @date: 2021/9/15
 */
@Component("picUtil")
public class PicUtil extends AbstractImage implements IPicToStrPic {

    private final Logger logger = LoggerFactory.getLogger(PicUtil.class);

    @Override
    public void toStrPic(InputStream inputStream, int precision, String formatName) {
        logger.info("开始转换{}图片", formatName);
        String base64 = "";
        String fileName = "";
        try {
            //输入流转换成 BufferedImage
            BufferedImage image = ImageIO.read(inputStream);
            //BufferedImage 转换成（加工后） base64 字符串
            base64 = this.picToBase64(image, precision, formatName);
            //base64 字符串转换成 BufferedImage
            BufferedImage bufferedImage = this.base64ToPic(base64);
            fileName = UUID.randomUUID() + "." + formatName;
            //创建文件
            ImageIO.write(bufferedImage, formatName, new File(fileName));
        } catch (IOException e) {
            logger.error("图片转换失败，base64：{}", base64, e);
        }
        logger.info("转换成功，文件名：{}", fileName);
    }
}
